package xin.baizhiedu.config;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import xin.baizhiedu.Util.DateTimeUtils;
import xin.baizhiedu.entity.*;
import xin.baizhiedu.Util.TimeUtils;
import xin.baizhiedu.Util.WebSocket;
import xin.baizhiedu.mapper.QGJobTaskTimeMapper;
import xin.baizhiedu.mapper.QGTableCompletionProcessMapper;
import xin.baizhiedu.mapper.QGTableYieldMapper;
import xin.baizhiedu.mapper.QGTimedTasksMapper;
import xin.baizhiedu.service.QgWorkScenceService;
import xin.baizhiedu.service.qgExcelService;
import xin.baizhiedu.service.qgJobWipService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@EnableScheduling
@Component
public class WebSocketScheduled {

    @Autowired
    private WebSocket webSocket;

    @Autowired
    private qgExcelService qgExcelService;

    @Autowired
    private qgJobWipService qgJobWipService;

    @Resource
    QGTableCompletionProcessMapper qGTableCompletionProcessMapper;

    @Resource
    QGTableYieldMapper qgTableYieldMapper;

    @Resource
    QGTimedTasksMapper qgTimedTasksMapper;

    @Resource
    QGJobTaskTimeMapper qgJobTaskTimeMapper;

    @Autowired
    QgWorkScenceService qgWorkScenceService;

    /**
     * 物料（工单）流转跟踪
     * @return
     */
    @Scheduled(cron = "0/20 * * * * ?")
    public void searchWorkOrderFlow() {
        String jsonString = JSON.toJSONString(qgWorkScenceService.searchWorkOrderFlow());
        webSocket.sendOneMessage("6", jsonString);

    }

    /**
     * 作业中心分布图
     * @return
     */
    @Scheduled(cron = "0/20 * * * * ?")
    public void searchWorkCenter() {
        String jsonString = JSON.toJSONString(qgWorkScenceService.searchWorkCenter());
        webSocket.sendOneMessage("7", jsonString);
    }

    /**
     * 在制工单完成情况
     * @return
     */
    @Scheduled(cron = "0/20 * * * * ?")
    public void searchWorkOrderCompletion() {
        String jsonString = JSONUtil.toJsonStr(qgWorkScenceService.searchWorkOrderCompletion());
        webSocket.sendOneMessage("8",jsonString);
    }

    @Scheduled(cron = "0/20 * * * * ?")
    public void heartbeat() {
        // 达成率
        BigDecimal Field4 = achievementRate(0);

        List<qgJobNuclearMaterial> qgJobNuclearMaterialList = qgExcelService.qgJobNuclearMaterialList();
        List<qgJobWeek> qgJobWeekList = qgExcelService.qgJobWeekList();
        qgJobWorking qgJobWorking = qgExcelService.qgJobWorkingOne();
        // 加工效率
        BigDecimal Field3 = processingEfficiency(0);

        long planNumSum = 0;
        long reciveNumSum = 0;
        long lastnNumSum = 0;
        for (qgJobNuclearMaterial i : qgJobNuclearMaterialList) {
            planNumSum = planNumSum + i.getPlanNum();
            reciveNumSum = reciveNumSum + i.getReciveNum();
            lastnNumSum = lastnNumSum + i.getLastNum();
        }
        BigDecimal bDividend = new BigDecimal(reciveNumSum);
        BigDecimal bDivisor = new BigDecimal(planNumSum);
        BigDecimal quotient = bDividend.divide(bDivisor, 3, RoundingMode.HALF_UP);
        BigDecimal end = new BigDecimal(qgJobWorking.getWanJob());
        BigDecimal qu = new BigDecimal(Long.parseLong(qgJobWorking.getWanJob()) + Long.parseLong(qgJobWorking.getKeepingJob()));
        BigDecimal Field6 = end.divide(qu, 3, RoundingMode.HALF_UP);
        DataList2 dataList2 = new DataList2();
        dataList2.setField3(Field3);
        dataList2.setField4(Field4);
        dataList2.setField5(quotient.multiply(BigDecimal.valueOf(100)));
        dataList2.setField6(Field6.multiply(BigDecimal.valueOf(100)));

        BigDecimal LastNum = new BigDecimal(Long.parseLong(qgJobWorking.getEndJob()) - Long.parseLong(qgJobWorking.getCountRepairJob()));
        BigDecimal EndJob = new BigDecimal(qgJobWorking.getEndJob());
        BigDecimal MeritRatio = BigDecimal.valueOf(1);
        if(!EndJob.equals(BigDecimal.ZERO)){
             MeritRatio = LastNum.divide(EndJob, 3, RoundingMode.HALF_UP);
        }
        PrecisionManufacturing precisionManufacturing = new PrecisionManufacturing();
        precisionManufacturing.setInstorageNumber(qgJobWorking.getEndJob());
        precisionManufacturing.setMeritRatio(MeritRatio.multiply(BigDecimal.valueOf(100)).setScale(1, RoundingMode.HALF_UP) + "%");
        precisionManufacturing.setUnfinishOrder(qgJobWorking.getKeepingJob());
        precisionManufacturing.setRepairNumber(qgJobWorking.getCountRepairJob());
        List<qgJobWeek> list = TimeUtils.getqgJobWeekList();
        for (qgJobWeek jobWeek : list) {
            for (qgJobWeek qgJobWeek : qgJobWeekList) {
                if (jobWeek.getStartTime().equals(qgJobWeek.getStartTime())) {
                    jobWeek.setTotal(qgJobWeek.getTotal());
                }
            }
        }
        precisionManufacturing.setList1(list);
        precisionManufacturing.setList2(dataList2);
        String jsonString = JSON.toJSONString(precisionManufacturing);
        webSocket.sendOneMessage("1", jsonString);
    }

    @Scheduled(cron = "0/20 * * * * ?")
    public void wip() {
        DataWip dataWip = new DataWip();
        List<qgJobWip> qgJobWipList = qgJobWipService.qgJobWipList();
        List<qgJobWorkstation> qgJobWorkstationlist = qgExcelService.qgJobWorkstationlist();

        List<WipList> wipList = new ArrayList<>();
        WipList wipList1=new WipList();
        WipList wipList2=new WipList();
        wipList1.setLabel("人工线");
        wipList2.setLabel("自动线");
        List<WipListData> WipListDatalist1 = new ArrayList<>();
        List<WipListData> WipListDatalist2 = new ArrayList<>();
        for (xin.baizhiedu.entity.qgJobWorkstation qgJobWorkstation : qgJobWorkstationlist) {
            WipListData WipListData = new WipListData();
            if (qgJobWorkstation.getManuType().equals("BOM.t_equi_manufactureunit.manu_type.workshop_station.003")) {
                WipListData.setText(qgJobWorkstation.getManuName());
                WipListData.setTotal(Long.parseLong(qgJobWorkstation.getJobTotal()));
                 WipListDatalist1.add(WipListData);
            }else{
                WipListData.setText(qgJobWorkstation.getManuName());
                WipListData.setTotal(Long.parseLong(qgJobWorkstation.getJobTotal()));
                WipListDatalist2.add(WipListData);
            }
        }
        wipList1.setList(WipListDatalist1);
        wipList2.setList(WipListDatalist2);
        wipList.add(wipList1);
        wipList.add(wipList2);
        dataWip.setList(wipList);
        BigDecimal FinishNumber = BigDecimal.valueOf(0);
        BigDecimal UnFinishNumber = BigDecimal.valueOf(0);
        for (xin.baizhiedu.entity.qgJobWip qgJobWip : qgJobWipList) {
            if (qgJobWip.getTypeJob() != null) {
                if (qgJobWip.getTypeJob().equals("BLOCK组件装配")) {
                    dataWip.setField3(BigDecimal.valueOf(100));
                    dataWip.setName3(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("IGS底层装配")) {
                    dataWip.setField4(BigDecimal.valueOf(100));
                    dataWip.setName4(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("底层测试")) {
                    dataWip.setField5(BigDecimal.valueOf(100));
                    dataWip.setName5(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("IGS二层装配")) {
                    dataWip.setField6(BigDecimal.valueOf(100));
                    dataWip.setName6(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("二层测试")) {
                    dataWip.setField7(BigDecimal.valueOf(100));
                    dataWip.setName7(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("柜体、柜门及附件装配")) {
                    dataWip.setField8(BigDecimal.valueOf(100));
                    dataWip.setName8(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("气管装配")) {
                    dataWip.setField9(BigDecimal.valueOf(100));
                    dataWip.setName9(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("线缆装配")) {
                    dataWip.setField10(BigDecimal.valueOf(100));
                    dataWip.setName10(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("保压测试")) {
                    dataWip.setField11(BigDecimal.valueOf(100));
                    dataWip.setName11(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("气柜氦检测/氦爆组")) {
                    dataWip.setField12(BigDecimal.valueOf(100));
                    dataWip.setName12(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("水氧测试")) {
                    dataWip.setField13(BigDecimal.valueOf(100));
                    dataWip.setName13(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("颗粒测试")) {
                    dataWip.setField14(BigDecimal.valueOf(100));
                    dataWip.setName14(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("气柜功能测试组")) {
                    dataWip.setField15(BigDecimal.valueOf(100));
                    dataWip.setName15(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("气体回填")) {
                    dataWip.setField16(BigDecimal.valueOf(100));
                    dataWip.setName16(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("气柜整理")) {
                    dataWip.setField17(BigDecimal.valueOf(100));
                    dataWip.setName17(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("气柜检验组")) {
                    dataWip.setField18(BigDecimal.valueOf(100));
                    dataWip.setName18(qgJobWip.getKeepingJob());
                }
                if (qgJobWip.getTypeJob().equals("气柜包装组")) {
                    dataWip.setField19(BigDecimal.valueOf(100));
                    dataWip.setName19(qgJobWip.getKeepingJob());
                }
            }
            FinishNumber = FinishNumber.add(qgJobWip.getTodayCompletedJob());
            UnFinishNumber = UnFinishNumber.add(qgJobWip.getKeepingJob());
            dataWip.setFinishNumber(FinishNumber);
            dataWip.setUnfinishNumber(UnFinishNumber);
        }
        String jsonString = JSON.toJSONString(dataWip);
         webSocket.sendOneMessage("2", jsonString);
    }

    @Scheduled(cron = "0/20 * * * * ?")
    public void NuclearMaterialKanban() {
        NuclearMaterialKanban nuclearMaterialKanban = new NuclearMaterialKanban();

        List<qgJobNuclearMaterial> qgJobNuclearMaterialList = qgExcelService.qgJobNuclearMaterialListWorking();
        List<qgJobWeekMateral> qgJobWeekMaterialList = qgExcelService.qgJobWeekMateral();
        List<Map<String, Object>> qgJobNuclearMaterialGroupBy  = qgExcelService.qgJobNuclearMaterialGroupBy();
        List<qgJobWeekMateral> qgJobWeekMaterial = TimeUtils.getQgJobWeekMateral();
        for (qgJobWeekMateral jobWeekMaterial : qgJobWeekMaterial) {
            for (xin.baizhiedu.entity.qgJobWeekMateral qgJobWeekMateral : qgJobWeekMaterialList) {
                if (jobWeekMaterial.getStartTime().equals(qgJobWeekMateral.getStartTime())) {
                    jobWeekMaterial.setTotal(qgJobWeekMateral.getTotal());
                }
            }
        }
        List<OrderEntry> list = new ArrayList<>();
        for (xin.baizhiedu.entity.qgJobNuclearMaterial qgJobNuclearMaterial : qgJobNuclearMaterialList) {
            OrderEntry orderEntry = new OrderEntry();
            orderEntry.setField1(qgJobNuclearMaterial.getJobCode());
            orderEntry.setField2(qgJobNuclearMaterial.getMateCode());
            orderEntry.setField3(qgJobNuclearMaterial.getJobEqname());
            orderEntry.setField4(String.valueOf(qgJobNuclearMaterial.getPlanNum()));
            orderEntry.setField5(String.valueOf(qgJobNuclearMaterial.getReciveNum()));
            orderEntry.setField6(String.valueOf(qgJobNuclearMaterial.getLastNum()));
            orderEntry.setField7(Math.toIntExact(qgJobNuclearMaterial.getReciveType()));
            list.add(orderEntry);
        }
        long UnfinishOrder = 0L;
        long FinishOrder = 0L;
        double FinishNumber =0;
        double UnfinishNumber =0;
        for (Map<String, Object> stringObjectMap : qgJobNuclearMaterialGroupBy) {
            FinishNumber = FinishNumber+ Double.parseDouble(stringObjectMap.get("NEEDNUM").toString());
            if (stringObjectMap.get("NEEDNUM").toString().equals(stringObjectMap.get("RECIVENUM").toString())) {
                FinishOrder=FinishOrder+1;
            }else{
                UnfinishOrder  =UnfinishOrder+1;
                UnfinishNumber = UnfinishNumber+ Double.parseDouble(stringObjectMap.get("LASTNUM").toString());
            }
        }
        nuclearMaterialKanban.setFinishNumber(String.valueOf(Math.ceil(FinishNumber-UnfinishNumber)));
        nuclearMaterialKanban.setFinishOrder(String.valueOf(FinishOrder));
        nuclearMaterialKanban.setUnfinishNumber(String.valueOf(Math.ceil(UnfinishNumber)));
        nuclearMaterialKanban.setUnfinishOrder(String.valueOf(UnfinishOrder));
        nuclearMaterialKanban.setList(list);
        nuclearMaterialKanban.setData(qgJobWeekMaterial);
        String jsonString = JSON.toJSONString(nuclearMaterialKanban);
        webSocket.sendOneMessage("3", jsonString);
    }

    @Scheduled(cron = "0/20 * * * * ?")
    public void Production() {
        qgJobWorkstationTotal qgJobWorkstationTotal= qgExcelService.getqgJobWorkstationTotal();
        qgJobCheck qgJobCheck= qgExcelService.qgJobCheck();
        qgJobYc qgJobYc= qgExcelService.qgJobYc();
        List<qgJobOrderWorking> qgJobOrderWorkinglist =qgExcelService.qgJobOrderWorkinglist("BOM.t_equi_manufactureunit.manu_type.workshop_station.003");
        List<qgJobOrderWorking> qgJobOrderWorkingOnelist= qgExcelService.qgJobOrderWorkingOne("BOM.t_equi_manufactureunit.manu_type.workshop_station.003");
        Production production= new Production();

        production.setProcessNumber(qgJobWorkstationTotal.getVcrTotal());
        production.setCompletedNumber(qgJobWorkstationTotal.getVcrTodayCompletedJob());
        production.setPlanNumber(qgJobWorkstationTotal.getVcrTodayPlanJob());

        BigDecimal bigDecimal= qgJobCheck.getVcrTotal().subtract(qgJobYc.getVcrTotal());
        production.setInspectNumber(String.valueOf(qgJobCheck.getVcrTotal()));
        if(qgJobCheck.getVcrTotal().equals(BigDecimal.ZERO)){
            production.setMeritRatio("100%");
        }else{
            production.setMeritRatio(bigDecimal.divide(qgJobCheck.getVcrTotal(), 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100))+"%");
        }
        production.setQualifiedNumber(String.valueOf(qgJobCheck.getVcrTotal().subtract(qgJobYc.getVcrTotal())));
        List<DataItem> list = new ArrayList<>();
        for (xin.baizhiedu.entity.qgJobOrderWorking qgJobOrderWorking : qgJobOrderWorkingOnelist) {
            DataItem dataItem = new DataItem();
            String jobCode = qgJobOrderWorking.getJobCode();
            List<qgJobOrderWorking> filteredList = qgJobOrderWorkinglist.stream().filter(item -> item.getJobCode().equals(jobCode)) .collect(Collectors.toList());
            for (int j = 0; j < filteredList.size(); j++) {
                if(filteredList.size()<=3){
                    dataItem.setField1(filteredList.get(j).getMateSerialnumber());
                    dataItem.setField2(filteredList.get(j).getMateCode());
                    if(j==0){
                        dataItem.setField3(JobTable(filteredList, j));
                        dataItem.setName3(filteredList.get(j).getJobName());
                    }
                    if(j==1){
                        dataItem.setField4(JobTable(filteredList, j));
                        dataItem.setName4(filteredList.get(j).getJobName());
                    }
                    if(j==2){
                        dataItem.setField5(JobTable(filteredList, j));
                        dataItem.setName5(filteredList.get(j).getJobName());
                    }
                }else if(j+3<=filteredList.size()){
                    if (filteredList.get(j).getStutStatename().equals("已完成")&&filteredList.get(j+1).getStutStatename().equals("已完成")&&filteredList.get(j+2).getStutStatename().equals("已完成")){

                    }else if(!filteredList.get(j).getStutStatename().equals("已完成")&&!filteredList.get(j).getStutStatename().equals("加工中")) {
                        dataItem.setField1(filteredList.get(j).getMateSerialnumber());
                        dataItem.setField2(filteredList.get(j).getMateCode());

                        dataItem.setField3(JobTable(filteredList, j));
                        dataItem.setName3(filteredList.get(j).getJobName());

                        dataItem.setField4(JobTable(filteredList, j+1));
                        dataItem.setName4(filteredList.get(j+1).getJobName());

                        dataItem.setField5(JobTable(filteredList, j+2));
                        dataItem.setName5(filteredList.get(j+2).getJobName());
                        break;
                    }else if(filteredList.get(j).getStutStatename().equals("加工中")) {
                        dataItem.setField1(filteredList.get(j).getMateSerialnumber());
                        dataItem.setField2(filteredList.get(j).getMateCode());
                        if(j==0){
                            dataItem.setField3(JobTable(filteredList, j));
                            dataItem.setName3(filteredList.get(j).getJobName());

                            dataItem.setField4(JobTable(filteredList, j+1));
                            dataItem.setName4(filteredList.get(j+1).getJobName());

                            dataItem.setField5(JobTable(filteredList, j+2));
                            dataItem.setName5(filteredList.get(j+2).getJobName());
                            break;
                        }else{
                            dataItem.setField3(JobTable(filteredList, j-1));
                            dataItem.setName3(filteredList.get(j-1).getJobName());

                            dataItem.setField4(JobTable(filteredList, j));
                            dataItem.setName4(filteredList.get(j).getJobName());

                            dataItem.setField5(JobTable(filteredList, j+2));
                            dataItem.setName5(filteredList.get(j+2).getJobName());
                            break;
                        }

                    }else {
                        dataItem.setField1(filteredList.get(j).getMateSerialnumber());
                        dataItem.setField2(filteredList.get(j).getMateCode());

                        dataItem.setField3(JobTable(filteredList, j));
                        dataItem.setName3(filteredList.get(j).getJobName());

                        dataItem.setField4(JobTable(filteredList, j+1));
                        dataItem.setName4(filteredList.get(j+1).getJobName());

                        dataItem.setField5(JobTable(filteredList, j+2));
                        dataItem.setName5(filteredList.get(j+2).getJobName());
                        break;
                    }
                }

            }
            list.add(dataItem);
        }
        production.setList(list);
        String jsonString = JSON.toJSONString(production);
        webSocket.sendOneMessage("4", jsonString);
    }

    @Scheduled(cron = "0/20 * * * * ?")
    public void MainLine()  {
        qgJobWorkstationTotal qgJobWorkstationTotal= qgExcelService.getqgJobWorkstationTotal();
        qgJobCheck qgJobCheck= qgExcelService.qgJobCheck();
        qgJobYc qgJobYc= qgExcelService.qgJobYc();
        List<qgJobOrderWorking> qgJobOrderWorkinglist =qgExcelService.qgJobOrderWorkinglist("BOM.t_equi_manufactureunit.manu_type.workshop_station.001");
        List<qgJobOrderWorking> qgJobOrderWorkingOnelist= qgExcelService.qgJobOrderWorkingOne("BOM.t_equi_manufactureunit.manu_type.workshop_station.001");
        Production production= new Production();
        production.setProcessNumber(qgJobWorkstationTotal.getIgsTotal());
        production.setCompletedNumber(qgJobWorkstationTotal.getIgsTodayCompletedJob());
        production.setPlanNumber(qgJobWorkstationTotal.getIgsTodayPlanJob());
        BigDecimal bigDecimal= qgJobCheck.getIgsTotal().subtract(qgJobYc.getIgsTotal());
        production.setInspectNumber(String.valueOf(qgJobCheck.getIgsTotal()));
        if(qgJobCheck.getIgsTotal().equals(BigDecimal.ZERO)){
            production.setMeritRatio("100%");
        }else {
            production.setMeritRatio(bigDecimal.divide(qgJobCheck.getIgsTotal(), 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)) + "%");

        }
        production.setQualifiedNumber(String.valueOf(qgJobCheck.getIgsTotal().subtract(qgJobYc.getIgsTotal())));
        List<DataItem> list = new ArrayList<>();
        for (xin.baizhiedu.entity.qgJobOrderWorking qgJobOrderWorking : qgJobOrderWorkingOnelist) {
            DataItem dataItem = new DataItem();
            String jobCode = qgJobOrderWorking.getJobCode();
            List<qgJobOrderWorking> filteredList = qgJobOrderWorkinglist.stream().filter(item -> item.getJobCode().equals(jobCode)) .collect(Collectors.toList());
            for (int j = 0; j < filteredList.size(); j++) {
                if(filteredList.size()<=3){
                    dataItem.setField1(filteredList.get(j).getMateSerialnumber());
                    dataItem.setField2(filteredList.get(j).getMateCode());
                    if(j==0){
                        dataItem.setField3(JobTable(filteredList, j));
                        dataItem.setName3(filteredList.get(j).getJobName());
                    }
                    if(j==1){
                        dataItem.setField4(JobTable(filteredList, j));
                        dataItem.setName4(filteredList.get(j).getJobName());
                    }
                    if(j==2){
                        dataItem.setField5(JobTable(filteredList, j));
                        dataItem.setName5(filteredList.get(j).getJobName());
                    }
                }else if(j+3<=filteredList.size()){
                    if (filteredList.get(j).getStutStatename().equals("已完成")&&filteredList.get(j+1).getStutStatename().equals("已完成")&&filteredList.get(j+2).getStutStatename().equals("已完成")){

                    }else if(!filteredList.get(j).getStutStatename().equals("已完成")&&!filteredList.get(j).getStutStatename().equals("加工中")) {
                        dataItem.setField1(filteredList.get(j).getMateSerialnumber());
                        dataItem.setField2(filteredList.get(j).getMateCode());

                        dataItem.setField3(JobTable(filteredList, j));
                        dataItem.setName3(filteredList.get(j).getJobName());

                        dataItem.setField4(JobTable(filteredList, j+1));
                        dataItem.setName4(filteredList.get(j+1).getJobName());

                        dataItem.setField5(JobTable(filteredList, j+2));
                        dataItem.setName5(filteredList.get(j+2).getJobName());
                        break;
                    }else if(filteredList.get(j).getStutStatename().equals("加工中")) {
                        dataItem.setField1(filteredList.get(j).getMateSerialnumber());
                        dataItem.setField2(filteredList.get(j).getMateCode());
                        if(j==0){
                            dataItem.setField3(JobTable(filteredList, j));
                            dataItem.setName3(filteredList.get(j).getJobName());

                            dataItem.setField4(JobTable(filteredList, j+1));
                            dataItem.setName4(filteredList.get(j+1).getJobName());

                            dataItem.setField5(JobTable(filteredList, j+2));
                            dataItem.setName5(filteredList.get(j+2).getJobName());
                            break;
                        }else{
                            dataItem.setField3(JobTable(filteredList, j-1));
                            dataItem.setName3(filteredList.get(j-1).getJobName());

                            dataItem.setField4(JobTable(filteredList, j));
                            dataItem.setName4(filteredList.get(j).getJobName());

                            dataItem.setField5(JobTable(filteredList, j+2));
                            dataItem.setName5(filteredList.get(j+2).getJobName());
                            break;
                        }

                    }else {
                        dataItem.setField1(filteredList.get(j).getMateSerialnumber());
                        dataItem.setField2(filteredList.get(j).getMateCode());

                        dataItem.setField3(JobTable(filteredList, j));
                        dataItem.setName3(filteredList.get(j).getJobName());

                        dataItem.setField4(JobTable(filteredList, j+1));
                        dataItem.setName4(filteredList.get(j+1).getJobName());

                        dataItem.setField5(JobTable(filteredList, j+2));
                        dataItem.setName5(filteredList.get(j+2).getJobName());
                        break;
                    }
                }

            }
            list.add(dataItem);
        }
        production.setList(list);
        String jsonString = JSON.toJSONString(production);
        webSocket.sendOneMessage("5", jsonString);
    }

    @Scheduled(cron = "0 10 0 * * ?") // 每天24点执行
    public void everyDay() throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        qgTimedTasks qgTimedTasks = new qgTimedTasks();
        qgTimedTasks.setCreateTime(formatter.parse(DateTimeUtils.ToDay(1)));
        qgTimedTasks.setYieldRate(yieldRate(1).toString());
        qgTimedTasks.setAchievementRate(achievementRate(1).toString());
        qgTimedTasks.setProcessingEfficiency(processingEfficiency(1).toString());
        String[] a =  pianNumber();
        String[] b =  completed();
        qgTimedTasks.setPlannedQuantity(a[0]);
        qgTimedTasks.setProductionNumber(a[1]);
        qgTimedTasks.setCompletedQuantity(b[0]);
        qgTimedTasks.setCompletedNumber(b[1]);
        qgTimedTasksMapper.insert(qgTimedTasks);
    }

    private int JobTable(List<qgJobOrderWorking> filteredList, int j) {
        int a =3;
       if (filteredList.get(j).getStutStatename().equals("已完成")) {
            a=1;
        } else if (filteredList.get(j).getStutStatename().equals("加工中")) {
            a=2;
        }
        if(filteredList.get(j).getAbnormalFlag()==null){

        } else if(filteredList.get(j).getAbnormalFlag().equals("1")){
            a=4;
        }
        return a;
    }

    private void WapperTable(QueryWrapper<QGTableYield> queryWrapper,int day) {
        String ToDay = DateTimeUtils.ToDay(day);
        queryWrapper.ge("JOB_ACTUALENDTIME", ToDay + " 00:00:00"); // ge 代表大于等于开始时间

        queryWrapper.le("JOB_ACTUALENDTIME", ToDay + " 23:59:59.999999999");   // le 代表小于等于结束时间
    }

    /**
     * 计划数  投产数
     */
    private String[] pianNumber(){
        String[] a = {"0","0"};
        QueryWrapper<qgJobTaskTime> wrapper = new QueryWrapper<>();
        wrapper.select("SUM( JOB_PLANNUM ) PLANNED_QUANTITY,\n" +
                "\tSUM( JOB_PRUDCTNUM ) PRODUCTION_NUMBER ");
        wrapper.eq("to_char(JOB_SCHEDULEDENDTIME,'yyyy-mm-dd')",DateTimeUtils.ToDay(0));
        List<Map<String, Object>> selectMaps = qgJobTaskTimeMapper.selectMaps(wrapper);
        System.out.println(selectMaps);
        if(selectMaps.get(0)!=null){
             a[0]=selectMaps.get(0).get("PLANNED_QUANTITY")==null?"":selectMaps.get(0).get("PLANNED_QUANTITY").toString();
             a[1]=selectMaps.get(0).get("PRODUCTION_NUMBER")==null?"":selectMaps.get(0).get("PRODUCTION_NUMBER").toString();
        }
        return a;
    }

    /**
     * 完成数量  已派数量
     */
    private String[] completed(){
        String[] a = {"0","0"};
        QueryWrapper<qgJobTaskTime> wrapper = new QueryWrapper<>();
        wrapper.select("SUM( JOB_ACTUALAMOUNT ) COMPLETED_QUANTITY,\n" +
                "\tSUM( JOB_ASSIGNEDQUANTITY ) COMPLETED_NUMBER ");
        wrapper.eq("to_char(JOB_ACTUALENDTIME,'yyyy-mm-dd')",DateTimeUtils.ToDay(0));
        List<Map<String, Object>> selectMaps = qgJobTaskTimeMapper.selectMaps(wrapper);
        if(selectMaps.get(0)!=null){
            a[0]=selectMaps.get(0).get("COMPLETED_QUANTITY")==null?"":selectMaps.get(0).get("COMPLETED_QUANTITY").toString();
            a[1]=selectMaps.get(0).get("COMPLETED_NUMBER")==null?"":selectMaps.get(0).get("COMPLETED_NUMBER").toString();
        }
        return a;
    }

    /**
     * 达成率
     */
    private BigDecimal achievementRate(int day){
        BigDecimal Field4 = new BigDecimal("1");
        QueryWrapper<QGTableYield> qgTableYieldQueryWrapper = new QueryWrapper<>();
        qgTableYieldQueryWrapper.select(" manu_name AS NAME,\n" +
                "\tCOUNT( CASE WHEN ABNORMAL_FLAG = 1 THEN 1 END ) AS ERR,\n" +
                "\tCOUNT( 1 ) AS TOTAL  ");
        WapperTable(qgTableYieldQueryWrapper,day);
        qgTableYieldQueryWrapper.groupBy("MANU_NAME");
        List<Map<String, Object>> selectMaps= qgTableYieldMapper.selectMaps(qgTableYieldQueryWrapper);
        for (Map<String, Object> selectMap : selectMaps) {
            BigDecimal ERR = (BigDecimal) selectMap.get("ERR");
            BigDecimal TOTAL = (BigDecimal) selectMap.get("TOTAL");
            Field4 = Field4.multiply(TOTAL.subtract(ERR).divide(TOTAL, 3, RoundingMode.HALF_UP));
        }
        return Field4.multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP);
    }

    /**
     * 良率
     */
    private BigDecimal yieldRate(int day){
        BigDecimal Field4 = new BigDecimal("1");
        QueryWrapper<QGTableYield> qgTableYieldQueryWrapper = new QueryWrapper<>();
        qgTableYieldQueryWrapper.select(" manu_name AS NAME,\n" +
                "\tCOUNT( CASE WHEN ABNORMAL_FLAG = 1 THEN 1 END ) AS ERR,\n" +
                "\tCOUNT( 1 ) AS TOTAL  ");
        WapperTable(qgTableYieldQueryWrapper,day);
        qgTableYieldQueryWrapper.groupBy("MANU_NAME");
        List<Map<String, Object>> selectMaps= qgTableYieldMapper.selectMaps(qgTableYieldQueryWrapper);
        BigDecimal ERR = new BigDecimal("0");
        BigDecimal TOTAL = new BigDecimal("0");
        for (Map<String, Object> selectMap : selectMaps) {
            ERR = ERR.add((BigDecimal) selectMap.get("ERR"));
            TOTAL = TOTAL.add((BigDecimal) selectMap.get("TOTAL"));
        }
        if(ERR.compareTo(BigDecimal.ZERO) > 0){
            Field4 = (TOTAL.subtract(ERR)).divide(TOTAL ,3, RoundingMode.HALF_UP);
        }
        return Field4.multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP);
    }

    /**
     * 加工效率
     */
    private  BigDecimal processingEfficiency(int day) {
        BigDecimal Field3 = new BigDecimal("1");
        QueryWrapper<QGTableCompletionProcess> queryWrapper = new QueryWrapper<>();
        String ToDay = DateTimeUtils.ToDay(day);
        queryWrapper.select("SUM( ROUND( actual_job_time, 2 ) ) AS ACTUAL_JOB_TIME,SUM( ROUND( plan_job_time, 2 ) ) AS PLAN_JOB_TIME ");
        queryWrapper.ge("JOB_ACTUALENDTIME", ToDay + " 00:00:00"); // ge 代表大于等于开始时间
        queryWrapper.le("JOB_ACTUALENDTIME", ToDay + " 23:59:59.999999999");   // le 代表小于等于结束时间
        queryWrapper.groupBy("STUT_STATENAME");
        List<Map<String, Object>> mapList= qGTableCompletionProcessMapper.selectMaps(queryWrapper);
        BigDecimal a = new BigDecimal("0");
        BigDecimal b =new BigDecimal("0");
        for (Map<String, Object> stringObjectMap : mapList) {
            a = (BigDecimal) stringObjectMap.get("ACTUAL_JOB_TIME");
            b = (BigDecimal) stringObjectMap.get("PLAN_JOB_TIME");
        }
        if(mapList.size()>0&& (a.compareTo(BigDecimal.ZERO) > 0)){
            Field3 = b.divide(a, 3, RoundingMode.HALF_UP);
        }
        return Field3.multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP);
    }


}